<template>
  <div class="editor-container">
    <script :id="editorId" name="content" type="text/plain"/>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth'

export default {
  name: 'Editor',
  components: { },
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-ueditor-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      editorId: this.id,
      editor: null
    }
  },
  computed: {
  },
  watch: {
    value(newval, oldval) {
      // if (oldval == '') {
      //   this.editor.setContent(this.value)
      // }
      setTimeout(() => {
        if (oldval === '') {
          this.editor.setContent(this.value)
        }
      },250)
    }
  },
  mounted() {
    // this.$nextTick(function () {
      this.initEditor();
    // })
  },
  activated() {
    this.initEditor()
  },
  deactivated() {
    this.destroyEditor()
  },
  destroyed() {
    this.destroyEditor()
  },
  methods: {
    initEditor() {
      // console.log(this.value)
      this.editor = window.UE.getEditor(this.editorId, {
        theme: 'gray',
        zIndex: 0,
        autoFloatEnabled: false,
        autoHeightEnabled: false,
        initialFrameWidth: '100%',
        initialFrameHeight: this.height,
        serverUrl: process.env.BASE_API + '/ueditor/index'
      }) // 初始化UE

      this.editor.ready(() => {
        this.editor.execCommand('serverparam', {
          'X-Token': getToken()
        })
      })
      this.editor.addListener('contentChange', () => {
        this.$emit('input', this.editor.getContent())
      })
    },
    destroyEditor() {
      this.editor.destroy()
    }
  }
}
</script>

<style scoped>

.editor-container *,
.editor-container *:before,
.editor-container *:after {
  box-sizing: content-box;
}

</style>
